var express = require('express');
const moment = require('moment');
const AccountModule = require('../../models/AccountModel');
const checkLoginMiddleware = require('../../middlewares/checkLoginMiddleware')

var router = express.Router();
/* GET home page. */
router.get('/', checkLoginMiddleware, function(req, res, next) {
  res.render('index/index', {title: "记账本", username: req.session.username});
});

router.get('/account', checkLoginMiddleware, function(req, res, next) {
  
  AccountModule.find()
  .sort({time: -1})
  .then(data => {
    res.render('index/list', {accounts: data, moment});
  }).catch(err => {
    console.log(err);
    res.send('404')
  });
  
});

router.get('/account/create', checkLoginMiddleware, function(req, res, next) {
  res.render('index/create');
});

router.post('/account', checkLoginMiddleware, function(req, res, next) {
  let time = moment(new Date(req.body.time));
  AccountModule.create({
    ...req.body,
    time
  }).then(data => {
    console.log(data);
    res.render('success', {msg:'添加成功', url:'/account'});
  }).catch(err => {
    console.log(err);
    res.send('404')
  });
  
});

router.get('/account/:id', checkLoginMiddleware, function(req, res, next) {
  let id = req.params.id;

  AccountModule.deleteOne({_id: id})
  .then(data => {
    console.log('删除了：', data);
    res.render('success', {msg:'删除成功', url:'/account'});
  }).catch(err => {
    res.send('删除失败')
    console.log(err);
  });

  
});



module.exports = router;
